﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace CoffeePotServer
{
    public class Client_Handler
    {
        #region Attributes
        private Socket _sktClient;
        private NetworkStream _netStream;
        private Server_Response _serverResponse;
        private Client_Response _clientResponse;
        #endregion

        #region Constructor
        /// <summary>
        /// Create an object to deal with client interation.
        /// </summary>
        /// <param name="thisSocket"></param>
        public Client_Handler(Socket thisSocket)
        {
            _sktClient = thisSocket;
            _netStream = new NetworkStream(thisSocket, true);
            _serverResponse = new Server_Response(_netStream);
            _clientResponse = new Client_Response(_netStream, _sktClient);
        }
        #endregion

        #region Properties
        public String Hostname
        {
            get { return Dns.GetHostEntry(((IPEndPoint)_sktClient.RemoteEndPoint).Address).HostName; }
        }
        #endregion

        #region Methods
        public void HandleClient()
        {
            String strClientResponse = "";
            do
            {
                strClientResponse = _clientResponse.ReadLine();
                if(HTCPCPServer.DebugMode && strClientResponse != "") Console.Write("[{0}] {1}: {2}",
                                                                                    DateTime.Now.ToLongTimeString(),
                                                                                    this.Hostname,
                                                                                    strClientResponse);
                _serverResponse.SendLine(strClientResponse);
            } while (_sktClient.Connected && _netStream.CanRead && strClientResponse != "");
            Console.WriteLine("[{0}] {1} Diconnected",
                              DateTime.Now.ToLongTimeString(),
                              this.Hostname);
        }
        #endregion
    }
}
